app.controller('shopDetailEditCtrl',['$scope','$filter','$state','$timeout','shopDetailEditService','toaster',function($scope,$filter,$state,$timeout,shopDetailEditService,toaster){
    $scope.headerQueue = [];
    $scope.bannerQueue = [];
    $scope.backQueue=[];
    $scope.headerImages=new Array();
    $scope.backImages=new Array();
    $scope.bannerImages=new Array();
    $scope.path=$scope.app.image.shop;
    $scope.shop={address:'',description:''}

    //查询日期
    $scope.weeks=[{name:'周一',state:false},{name:'周二',state:false},{name:'周三',state:false},{name:'周四',state:false},{name:'周五',state:false},{name:'周六',state:false},{name:'周日',state:false}];
    $scope.times=['0:00','1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'];


    //查询店铺信息
    $scope.findinfo=function(){
        shopDetailEditService.findinfo($scope).then(function (result) {
            $scope.bannerLimit=5;
            $scope.headerLimit=1;
            $scope.backLimit=1;

            switch (result.status){
                case 200:
                    var sp=$scope.shop=result.data;
                    var lnglat={};

                    //设置地址定位
                    lnglat.P=sp.lat;
                    lnglat.O=sp.lng;
                    lnglat.lat=sp.lat;
                    lnglat.lng=sp.lng;
                    marker.setPosition(lnglat);
                    map.setCenter(marker.getPosition());

                    if($scope.shop.openingDays!=null || angular.isUndefined($scope.shop.openingDays)){
                        openDay($scope.shop.openingDays);
                    }

                    $scope.selectProvice=$scope.shop.provinceName;
                    $scope.selectTown=$scope.shop.cityName;
                    $scope.selectCounty=$scope.shop.countyName;

                    if(sp.bannerImages!=null){
                        $scope.bannerLimit-=sp.bannerImages.length;
                    }
                    $scope.bannerImages=sp.bannerImages;

                    if(!angular.isUndefined(sp.shopHeadImgUrl)&& sp.shopHeadImgUrl!=null){
                        if($scope.headerImages.length<=0){
                            $scope.headerImages.push(sp.shopHeadImgUrl);
                        }
                        $scope.headerLimit=0;
                    }else{
                        $scope.headerImages.splice(0,$scope.headerImages.length);
                    }


                    if(!angular.isUndefined(sp.backgroundImage)&& sp.backgroundImage!=null){
                        if($scope.backImages.length<=0){
                            $scope.backImages.push(sp.backgroundImage);
                        }
                        $scope.backLimit=0;
                    }else{
                        $scope.backImages.splice(0,$scope.backImages.length);
                    }
                    if($scope.shop.address==null){
                        $scope.shop.address='';
                    }
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    $scope.findinfo();

    //修改周期
    var selectWeek=function(){
        var day='';
        for(var i=0;i<$scope.weeks.length;i++){
            if($scope.weeks[i].state){
                day+=$scope.weeks[i].name+',';
            }
        }
        var index=day.lastIndexOf(',');
        if(index>-1){
            day=day.substring(0,index);
        }
        return day;
    };

    //循环改变日期
    var openDay=function(openDays){
        var days=openDays.split(',');
        for(var i=0;i<$scope.weeks.length;i++){
            var index=days.indexOf($scope.weeks[i].name);
            if(index>-1){
                $scope.weeks[i].state=true;
            }
        }
    };


    shopDetailEditService.shopEditVO.lat=0.00;
    shopDetailEditService.shopEditVO.lng=0.00;

    //修改店铺信息
    $scope.updateShop=function(){
        var sv=shopDetailEditService.shopEditVO;

        sv.name=$scope.shop.name;
        sv.mobilePhone=$scope.shop.mobilePhone;
        sv.address=$scope.shop.address;
        sv.description=$scope.shop.description;
        sv.areaProvinceId=$scope.shop.areaProvinceId;
        sv.areaCityId=$scope.shop.areaCityId;
        sv.areaCountyId=$scope.shop.areaCountyId;
        if($scope.shop.lat!=null){
            sv.lat=$scope.shop.lat;
        }
        if($scope.shop.lng!=null){
            sv.lng=$scope.shop.lng;
        }
        sv.auditStatus=$scope.shop.auditStatus;
        sv.status=$scope.shop.status;
        sv.openingHours=$scope.shop.startTime+'-'+$scope.shop.endTime;
        sv.openingDays=selectWeek();

        if($scope.headerQueue.length>0){
            sv.shopHeadImgUrl=$scope.headerQueue[0].fileName;
        }

        if($scope.backQueue.length>0){
            sv.backgroundImage=$scope.backQueue[0].fileName;
        }

        for(var i=0;i<$scope.bannerQueue.length;i++){
            sv.bannerImages.push($scope.bannerQueue[i].fileName);
        }

        if(sv.auditStatus == 0 || sv.auditStatus == 1){
            delete sv.status;
        }

        $scope.updateState=false;

        shopDetailEditService.updateShop($scope).then(function(result){
            if($scope.updateState){
                return;
            }

            $scope.updateState=true;

            switch (result.status){
                case 200:
                    toaster.pop('success', "提示", "操作成功");

                    $scope.headerQueue.splice(0,$scope.headerQueue.length);
                    $scope.bannerQueue.splice(0,$scope.bannerQueue.length);
                    sv.bannerImages.splice(0,sv.bannerImages.length);
                    $scope.updateState=false;
                    $state.go('app.shopDatum');
                    break;
                default :
                    $scope.updateState=false;
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })

    }

    //删除头像
    $scope.delShopHeaderImages= function (url) {
        shopDetailEditService.delShopHeaderImages($scope,url).then(function(result){
            switch (result.status){
                case 200:
                    toaster.pop('success', "提示", "操作成功");
                    $scope.findinfo();
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    $scope.delBackgroundImage= function (url) {
        shopDetailEditService.delBackgroundImage($scope,url).then(function(result){
            switch (result.status){
                case 200:
                    toaster.pop('success', "提示", "操作成功");
                    $scope.findinfo();
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }

    //删除广告图
    $scope.delBannerImages= function (url) {
        shopDetailEditService.delBannerImages($scope,url).then(function(result){
            switch (result.status){
                case 200:
                    toaster.pop('success', "提示", "操作成功");
                    $scope.findinfo();
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        })
    }


    $scope.currentState=4;
    $scope.selectCounty=null;
    $scope.selectTown=null;
    $scope.selectProvice="省";
    $scope.selectTown="市";
    $scope.selectCounty="区";
    $scope.showState=false;
    $scope.towns=[];
    $scope.countys=[];
    $scope.steps={percent:20, step1:true, step2:false, step3:false};

    $scope.findProvinces=function(level,parentId){
        $scope.showState=!$scope.showState;

        if($scope.showState){
            $scope.selectState=true;
            if($scope.currentState==0){
                $scope.currentState=1;
            }
            $scope.findArea(level,parentId);
        }
    }

    $scope.findTown=function(level,item){
        $scope.findArea(level,item.cityId,item.name);
        $scope.shop.areaProvinceId=item.id;
        $scope.changeArea();
    }

    $scope.findCounty=function(level,item){
        $scope.findArea(level,item.cityId,item.name);
        $scope.shop.areaCityId=item.id;
        $scope.changeArea();
    }

    $scope.CountyHide=function(item){
        $scope.selectCounty=item.name;
        $scope.shop.areaCountyId=item.id;
        $scope.showState=false;
        $scope.changeArea();
        $scope.currentState=4;
    }

    $scope.changeCurrent=function(index){
        $scope.currentState=index;
    }

    $scope.findArea=function(level,parentId,name){
        shopDetailEditService.findArea($scope,level,parentId,name).then(function(result){
            switch (result.status){
                case 200:
                    if(level==0){
                        $scope.provinces=result.data;
                    }else if(level==1){
                        $scope.towns=result.data;
                        $scope.currentState=2;
                        $scope.selectProvice=name;
                        $scope.selectTown="市";
                        $scope.selectCounty="区";
                        $scope.steps.step2=true;
                    }else if(level==2){
                        $scope.countys=result.data;
                        $scope.currentState=3;
                        $scope.selectTown=name;
                        $scope.selectCounty="区";
                        $scope.steps.step3=true;
                    }
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break;
            }
        });
    }

    $scope.changeArea=function(){
        $scope.newArea=$scope.selectProvice+$scope.selectTown+$scope.selectCounty;
    }




    //地图加载
    $scope.addressState=0;
    var map = new AMap.Map('container',{
        resizeEnable: false,
        zoom: 13,
        center: [116.39,39.9]
    });
    //工具条
    map.plugin(["AMap.ToolBar"], function() {
        map.addControl(new AMap.ToolBar());
    });

    //拾取位置
    AMap.service('AMap.Geocoder',function(){
        //实例化Geocoder
        geocoder = new AMap.Geocoder({
            city: "010"//城市，默认：“全国”
        });
    })

    var marker = new AMap.Marker({
        map:map,
        bubble:true
    })

    map.on('click',function(e){
        marker.setPosition(e.lnglat);
        $scope.shop.lat=e.lnglat.lat;
        $scope.shop.lng=e.lnglat.lng;

        geocoder.getAddress(e.lnglat,function(status,result){
            if(status=='complete'){
                $scope.$apply(function () {
                    $scope.shop.address=result.regeocode.formattedAddress;
                    $scope.addressState=3;
                });
            }
        })
    })




    var placeSearch = new AMap.PlaceSearch({
        map: map,
        pageSize: 5,
        pageIndex: 1,
        city: "全国", 
        // panel: "panel",
        typ:'餐饮服务'
    });  

    $scope.getAddressPos=function(){
        var address=$scope.shop.address;
        placeSearch.search(address, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                if(result.poiList.pois.length>1){
                    $scope.$apply(function () {
                        $scope.addressState=1;
                    });
                }else{
                    $scope.$apply(function () {
                        $scope.addressState=3;
                        $scope.shop.lat=result.poiList.pois[0].location.lat;
                        $scope.shop.lng=result.poiList.pois[0].location.lng;
                    });
                }
            }else{
                $scope.addressState=2;
            }
        });
    }

    var timeout;

    $scope.site=function(){
        placeSearch.search($scope.shop.address, function(status, result) {
            if(status==='complete'){
                if(result.poiList.pois.length>1){
                    $scope.$apply(function () {
                        $scope.addressState=1;
                    });
                }else{
                    $scope.$apply(function () {
                        $scope.addressState=3;
                        $scope.shop.lat=result.poiList.pois[0].location.lat;
                        $scope.shop.lng=result.poiList.pois[0].location.lng;
                    });
                }
            }
        });

        //搜索单击
        AMap.event.addListener(placeSearch, "markerClick", function(e){
            $scope.$apply(function () {
                $scope.shop.address=e.data.address;
                $scope.shop.lat= e.event.lnglat.lat;
                $scope.shop.lng=e.event.lnglat.lng;
                $scope.addressState=3;
            });
        });


    }

}])